package com.wulin;

import com.wulin.mapper.UserDataMapper;
import com.wulin.pojo.UserData;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JPasswordField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

public class zhuce_system extends JFrame {

	private JPanel contentPane;
	private JTextField textField;
	private JTextField textField_2;
	private JTextField textField_3;
	private JPasswordField passwordField;
	private JPasswordField passwordField_1;
//	JbdcObdcConnection db=new JbdcObdcConnection();
	String resource = "mybatis-config.xml";
	InputStream inputStream = Resources.getResourceAsStream(resource);
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

	SqlSession sqlSession =sqlSessionFactory.openSession();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					zhuce_system frame = new zhuce_system();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	/**
	 * Create the frame.
	 */
	public zhuce_system() throws IOException {
		getContentPane().setLayout(null);
//		db = new JbdcObdcConnection();
//        db.getConnection();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 597, 714);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel label = new JLabel("注册用户");
		label.setFont(new Font("宋体", Font.PLAIN, 30));
		label.setBounds(211, 44, 120, 37);
		contentPane.add(label);
		
		JLabel label_1 = new JLabel("用户名：");
		label_1.setFont(new Font("宋体", Font.PLAIN, 24));
		label_1.setBounds(42, 88, 134, 34);
		contentPane.add(label_1);
		
		textField = new JTextField();
		textField.setColumns(10);
		textField.setBounds(191, 92, 159, 32);
		contentPane.add(textField);
		
		JLabel label_2 = new JLabel("密   码：");
		label_2.setFont(new Font("宋体", Font.PLAIN, 26));
		label_2.setBounds(42, 137, 120, 34);
		contentPane.add(label_2);
		
		passwordField = new JPasswordField();
		passwordField.setBounds(191, 139, 159, 32);
		contentPane.add(passwordField);
		
		JLabel label_3 = new JLabel("邮  箱：");
		label_3.setFont(new Font("宋体", Font.PLAIN, 26));
		label_3.setBounds(42, 224, 120, 29);
		contentPane.add(label_3);
		
		textField_2 = new JTextField();
		textField_2.setColumns(10);
		textField_2.setBounds(191, 223, 159, 32);
		contentPane.add(textField_2);
		
		JLabel label_4 = new JLabel("手机号：");
		label_4.setFont(new Font("宋体", Font.PLAIN, 26));
		label_4.setBounds(42, 268, 114, 29);
		contentPane.add(label_4);
		
		textField_3 = new JTextField();
		textField_3.setColumns(10);
		textField_3.setBounds(191, 270, 159, 32);
		contentPane.add(textField_3);
		
		JLabel label_5 = new JLabel("用户类型");
		label_5.setFont(new Font("宋体", Font.PLAIN, 26));
		label_5.setBounds(42, 324, 120, 37);
		contentPane.add(label_5);
		
		JComboBox comboBox = new JComboBox();
		comboBox.setModel(new DefaultComboBoxModel(new String[] {"管理员", "普通农户", "农业专家"}));
		comboBox.setBounds(191, 326, 159, 32);
		contentPane.add(comboBox);
		
		JButton button = new JButton("注册");
		button.setFont(new Font("宋体", Font.PLAIN, 26));
		
		button.setBounds(104, 419, 303, 91);
		contentPane.add(button);
		
		JLabel label_6 = new JLabel("确认密码：");
		label_6.setFont(new Font("宋体", Font.PLAIN, 26));
		label_6.setBounds(42, 179, 134, 37);
		contentPane.add(label_6);
		
		passwordField_1 = new JPasswordField();
		passwordField_1.setBounds(191, 180, 159, 32);
		contentPane.add(passwordField_1);
		
		button.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {

				try {
					String username = textField.getText();
					String password = new String(passwordField.getText());
					String confirmPassword = new String(passwordField_1.getText());
					String email = textField_2.getText();
					String phone = textField_3.getText();
					String userType = comboBox.getSelectedItem().toString();
					LocalDateTime registrationTime = LocalDateTime.now();
					if (!password.equals(confirmPassword)) {
						JOptionPane.showMessageDialog(zhuce_system.this,
								"密码和确认密码不匹配", "错误", JOptionPane.ERROR_MESSAGE);
						return;
					}
					UserData user = new UserData();
					user.setUsername(username);
					user.setPassword(password);
					user.setUsertype(userType);
					user.setContact_information(email + " " + phone);
					user.setRegistration_time(String.valueOf(registrationTime));

					UserDataMapper mapper = sqlSession.getMapper(UserDataMapper.class);
					int rows = mapper.insert(user);
					if (rows > 0) {
						JOptionPane.showMessageDialog(zhuce_system.this, "注册成功", "成功", JOptionPane.INFORMATION_MESSAGE);
					} else {
						JOptionPane.showMessageDialog(zhuce_system.this, "注册失败", "失败", JOptionPane.ERROR_MESSAGE);
					}
					sqlSession.commit();
				} catch (Exception ex) {
					ex.printStackTrace();
					JOptionPane.showMessageDialog(zhuce_system.this, "操作失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
					sqlSession.rollback();
				}
//
//	            boolean usernameExists = false;
//	            try {
//	                String sqlCheck = "SELECT COUNT(*) FROM user_data WHERE username = ?";
//	                try (
//	                    PreparedStatement pstmtCheck = db.prepareStatement(sqlCheck)) {
//	                    pstmtCheck.setString(1, username);
//	                    ResultSet rs = pstmtCheck.executeQuery();
//	                    if (rs.next()) {
//	                        int count = rs.getInt(1);
//	                        usernameExists = count > 0;
//	                    }
//	                }
//	            } catch (SQLException ex) {
//	                ex.printStackTrace();
//	                JOptionPane.showMessageDialog(zhuce_system.this, "数据库查询失败", "错误", JOptionPane.ERROR_MESSAGE);
//	                return;
//	            }
//
//	            if (usernameExists) {
//	                JOptionPane.showMessageDialog(zhuce_system.this, "用户名已存在，请更换", "错误", JOptionPane.ERROR_MESSAGE);
//	                return;
//	            }
//
//	            if (!password.equals(confirmPassword)) {
//	                JOptionPane.showMessageDialog(zhuce_system.this,
//	                        "密码和确认密码不匹配", "错误", JOptionPane.ERROR_MESSAGE);
//	                return;
//	            }
//
//	            if(email.isEmpty() && phone.isEmpty()){
//	            	JOptionPane.showMessageDialog(zhuce_system.this,
//                            "注册失败，请重试", "失败", JOptionPane.ERROR_MESSAGE);
//	            }
//	            else{
//	            	String sql = "INSERT INTO user_data (username, password, user_type, contact_information, registration_time) VALUES ('"+ username +"', '"+ password +"', '"+ userType +"', '"+ contact_Infomation +"','"+registrationTime+"')";
//	 	            boolean rowsAffected = db.executeUpdate(sql);
//	                 if (rowsAffected) {
//	                 	JOptionPane.showMessageDialog(zhuce_system.this,
//	                             "注册成功", "成功", JOptionPane.INFORMATION_MESSAGE);
//	                 } else {
//	                 	JOptionPane.showMessageDialog(zhuce_system.this,
//	                             "注册失败，请重试", "失败", JOptionPane.ERROR_MESSAGE);
//	                 }
//	            }
	           
			}
		});
		
	}
}
